﻿

using Qy_CSharp_NetWork.Component;
using QyCsharpProgramTools.User32.Apply;
using QyTimeController.Component;
using RenderHeads.Media.AVProVideo;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class GameManager : MonoBehaviour
{
    private const bool PRGRESS_DEBUG = true;
    private const string GAME_ID = "5";
    public const string TIME_FORMAT = "yyyy/MM/dd/HH:mm:ss.fff";

    [SerializeField]
    private MediaPlayer m_mediaPlayer;
    [SerializeField]
    private ObjManager m_objManager;
    private TimerComponentForUnity m_timeController;


    private DateTime _pStartExe;
    private DateTime _pStartAt;
    private long _pTimeOfExe;
    private long m_qyStarProcessTime;
    private long m_buildInGameTime;
    private long m_startAtTime = 0;
    private long m_movieTime = 15;
    private long m_readyTime = 8;                           //准备时间 数字 ‘10’ 以下 ！！
    private long m_gameTime = 10;
    private long m_lastTime = 10;

    private void Awake()
    {
        //记录开始时间(计时器)
        _pStartExe = DateTime.Now;
        Application.runInBackground = true;
        Debug.unityLogger.logEnabled = PRGRESS_DEBUG;

        m_timeController = this.gameObject.AddComponent<TimerComponentForUnity>();
        m_qyStarProcessTime = TimerComponentForUnity.GetCurTimetamp();
        m_buildInGameTime = m_startAtTime + m_movieTime + m_readyTime + m_gameTime + m_lastTime;
    }
    private void Start()
    {
        //  加载视频
        m_mediaPlayer.Events.AddListener((p, t, e) =>
        {
            if (t == MediaPlayerEvent.EventType.ReadyToPlay)
            {
                Debug.Log("Media movie has ready.");
                m_InitGame();
            }
        });
        m_mediaPlayer.m_Loop = false;
        m_mediaPlayer.OpenVideoFromFile(MediaPlayer.FileLocation.RelativeToStreamingAssetsFolder, m_GetVideoName(), false);
    }

    private string m_GetVideoName()
    {
        var dir = new DirectoryInfo(Application.streamingAssetsPath);
        var files = dir.GetFiles();
        foreach (var f in files)
        {
            if (f.Name.Contains(".mp4"))
            {
                return f.Name;
            }
        }
        return "";
    }
    private void m_InitGame()
    {
        var inputValue = InputParamController.GetInputValue();
        Debug.Log("Token : " + inputValue.token);
        Debug.Log("duration : " + inputValue.duration);
        Debug.Log("startat : " + inputValue.startat.ToString(InputParamController.TIME_FORMAT));
        Debug.Log("timeoffset : " + inputValue.timeoffset);
        Debug.Log("mysterious : " + inputValue.mysterious);
        Debug.Log("device : " + inputValue.device);

        _pTimeOfExe = inputValue.duration;
        _pStartAt = inputValue.startat;

        var movieTime = m_mediaPlayer.Info.GetDurationMs();
        m_AddTaskWithTime((long)movieTime);
        NetWorkController.instance.Receive.BuildRoomSuccEvent += BuildRoomSuccessCallBack;
        m_StartNetWork(inputValue.token, GAME_ID, inputValue.device, NET_OPTION.WAN, true);
    }

    private void m_AddTaskWithTime(long movieMilliSecond)
    {
        long _startAtTime = m_startAtTime * 1000;               //开启游戏时间
        long _movieTime = m_movieTime * 1000;                   //视频时间
        long _readyTime = m_readyTime * 1000;                   //准备时间
        long _gameTime = m_gameTime * 1000;                     //游戏时间
        long _lastTime = m_lastTime * 1000;                     //汇总时间
        //取参数后的游戏时长
        long paramAllTime = (long)((_pStartAt - _pStartExe).TotalMilliseconds + _pTimeOfExe * 1000);
        Debug.LogWarning("---启动EXE时间 ：" + _pStartExe.ToString(TIME_FORMAT));
        Debug.LogWarning("---游戏开始时间：" + _pStartAt.ToString(TIME_FORMAT));
        Debug.LogWarning("---开始与启动差：" + (_pStartAt - _pStartExe).TotalMilliseconds);
        Debug.LogWarning("---游戏    时长：" + _pTimeOfExe * 1000);
        Debug.LogWarning("---可用游戏时间：" + paramAllTime + "  游戏内置时间 ：" + m_buildInGameTime * 1000);
        //开始游戏时间 - 启动EXE时间 + 需要玩的时间 < 游戏内置时间
        if (paramAllTime < m_buildInGameTime * 1000)
        {
            Debug.LogWarning("请核查时间参数 ！！！！");
            Debug.LogWarning("程序停止 ！！！");
            Application.Quit();
            return;
        }
        _startAtTime = (long)(_pStartAt - _pStartExe).TotalMilliseconds;
        if (_startAtTime < 0)
            _startAtTime = 0;
        _movieTime = movieMilliSecond;
        _readyTime = m_readyTime * 1000;
        _lastTime = m_lastTime * 1000;
        _gameTime = (paramAllTime - _readyTime - movieMilliSecond - m_lastTime * 1000 - _startAtTime);
        m_gameTime = _gameTime / 1000;
        Debug.Log("_startAtTime:" + _startAtTime);
        Debug.Log("_movieTime:" + _movieTime);
        Debug.Log("_readyTime:" + _readyTime);
        Debug.Log("_gameTime:" + _gameTime);
        Debug.Log("_lastTime:" + _lastTime);

        long start_at = _startAtTime;
        long movie_done = start_at + _movieTime;
        long ready_done = movie_done + _readyTime;
        long game_done = ready_done + _gameTime;
        long gamg_over = game_done + _lastTime;


        var m_curreadyTime = (int)m_readyTime;

        m_timeController.AddTask("StartAt", start_at, (id, tag, type) =>
            {
                Debug.LogWarning(string.Format("id:{0}，tag:{1} ,type{2}", id, tag, type));
                m_OnStartAtTime();
            });
        m_timeController.AddTask("MovieTime", movie_done, (id, tag, type) =>
        {
            m_OnMovieTimeDone();
            Debug.LogWarning(string.Format("id:{0}，tag:{1} ,type{2}", id, tag, type));
        });
        m_timeController.AddLoopTask("ReadyTime", movie_done, ready_done, 1000, (id, tag, type) =>
         {
             switch (type)
             {
                 case TIME_EVENT_TYPE.LOOP_ENTER:
                 case TIME_EVENT_TYPE.LOOP_CONTINUE:
                     m_curreadyTime--;
                     m_objManager.ui_title.GetComponent<UI_Title>().SetReadyTime((int)m_curreadyTime);
                     break;
                 case TIME_EVENT_TYPE.LOOP_EXIT:
                     m_OnReadyTimeDone();
                     break;
             }

             Debug.LogWarning(string.Format("id:{0}，tag:{1} ,type{2}", id, tag, type));
         });
        m_timeController.AddTask("GimeTime", game_done, (id, tag, type) =>
        {
            m_OnGameTimeDone();
            Debug.LogWarning(string.Format("id:{0}，tag:{1} ,type{2}", id, tag, type));
        });
        m_timeController.AddTask("LastTime", gamg_over, (id, tag, type) =>
        {
            m_OnLastTimeDone();
            Debug.LogWarning(string.Format("id:{0}，tag:{1} ,type{2}", id, tag, type));
        });
        m_timeController.StartTimer(m_qyStarProcessTime);
    }


    private void m_OnStartAtTime()
    {
        Debug.Log(" @@@@@@@@ m_OnStartAtTime @@@@@@@@ ");
        Screen.SetResolution(1920, 1080, true);
        QyUser32Apply myprocess = new QyUser32Apply();
        IntPtr handle = myprocess.GetMainWindowHandle(System.Diagnostics.Process.GetCurrentProcess().Id);
        QyCsharpProgramTools.User32.ProtoType.QyProtoUser32.ShowWindow(handle, 3);
        Cursor.visible = false;
        m_objManager.ActiveMovie();
        m_mediaPlayer.Play();
    }
    //开房成功回调
    private void BuildRoomSuccessCallBack(object sender, EventArgs e)
    {
        BuildRoomInfo buildRoomInfo = e as BuildRoomInfo;
        m_objManager.ui_game.GetComponent<UI_Game>().SetQrCode(buildRoomInfo.qrCodeUrl);
        //建房成功、房间验证成功后，发送游戏状态 -- 1 -- 
        NetWorkController.instance.Send.PushGameStatus("1");
    }
    private void m_OnMovieTimeDone()
    {
        Debug.Log(" @@@@@@@@ m_OnMovieTimeDone @@@@@@@@ ");
        NetWorkController.instance.Send.PushGameStatus("2");
        m_objManager.ActiveTitle();
    }

    private void m_OnReadyTimeDone()
    {
        Debug.Log(" @@@@@@@@ m_OnReadyTimeDone @@@@@@@@ ");

        NetWorkController.instance.Send.PushGameStatus("3");
        m_objManager.ActiveGame();
    }
    private void m_OnGameTimeDone()
    {
        Debug.Log(" @@@@@@@@ m_OnGameTimeDone @@@@@@@@ ");
        NetWorkController.instance.Send.PushGameStatus("5");

        //   m_gameSceneController.ShowOver();
    }
    private void m_OnLastTimeDone()
    {
        Debug.Log(" @@@@@@@@ m_OnLastTimeDone @@@@@@@@ ");
        NetWorkController.instance.Send.PushGameStatus("6");

        m_StopAndDisposeNetWork();
        Debug.Log(DateTime.Now.ToString(TIME_FORMAT));
        Application.Quit();
    }

    private void m_StartNetWork(string pToken, string pGameId, string[] deviceIds, NET_OPTION option, bool isDebug)
    {
        NetWorkController.instance.Send.token = pToken;
        NetWorkController.instance.Send.gameId = pGameId;
        NetWorkController.instance.Send.needDebug = isDebug;
        if (deviceIds == null || deviceIds.Length == 0)
            NetWorkController.instance.Send.StartLAM(option);
        else
            NetWorkController.instance.Send.StartLAM(option, deviceIds);
    }
    private void m_StopAndDisposeNetWork()
    {
        NetWorkController.instance.Send.Dispose();
    }


}
